<template>
  <a-upload
    ref="uploadRef"
    @success="success"
    :auto-upload="props.autoUpload"
    @beforeUpload="beforeUpload"
    :accept="fileTypeList.join(',')"
    :listType="listType"
    :limit="limit"
    v-model:fileList="uploadList"
    :draggable="draggable"
    :tip="tip"
    @change="change"
    :custom-request="customRequest"
    :show-remove-button="props.showRemoveButton"
    :show-preview-button="props.showPreviewButton"
    :show-file-list="props.showFileList"
    :on-before-remove="beforeRemove"
  >
    <!-- <template #upload-button>
      <div>
        <a-button @click="handleUpload">Upload Files</a-button>
        <a-button @click="handleRemove">Remove Selected</a-button>
      </div>
    </template> -->
    <template #image="{ fileItem }">
      <icon-check-circle
        v-if="props.imgSelectedId === fileItem.response.fileId"
        :size="34"
        style="
          color: #77a7fa;
          position: absolute;
          z-index: 1000;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
        "
      />
      <a-popconfirm
        v-if="loginBgSetting"
        content="确定删除背景图片?"
        type="error"
        @ok="delImg(fileItem.response.fileId)"
      >
        <a-button
          style="
            color: #f80400;
            background: #eee;
            position: absolute;
            z-index: 1001;
            right: 1px;
            bottom: 1px;
            /* transform: translate(50%, -50%); */
          "
          type="text"
          status="danger"
        >
          <template #icon>
            <icon-delete />
          </template>
        </a-button>
      </a-popconfirm>

      <!-- <icon-delete :size="24" /> -->
      <div
        :class="[
          'img',
          props.imgSelectedId === fileItem.response.fileId
            ? 'img-selected'
            : '',
          props.hiddenMask ? 'hiddenMask' : ''
        ]"
        @click="setLoginBgImg(fileItem.response.fileId)"
      >
        <img :src="fileItem.url" />
      </div>
    </template>
  </a-upload>
  <!-- :custom-request="customRequest" -->
</template>

<script setup lang="ts">
import { cloneDeep } from 'lodash';
import { useUploadFileStore } from '@/store/index';
import { deleteFile } from '@/apis/document/documentCenter/index';
import { Message } from '@arco-design/web-vue';

export interface TFileItem {
  fileId: number;
  fileUrl: string;
  fileName: string;
}

const props = withDefaults(
  defineProps<{
    fileList?: TFileItem[]; //请求分页数据函数
    fileTypeList?: string[];
    maxSize?: number;
    limit?: number;
    listType?: 'picture' | 'text' | 'picture-card';
    draggable?: boolean;
    tip?: string;
    userId?: number;
    type?: number; //业务类型 1.组织2.人事3.考勤4.绩效5.薪酬6.合同7.审批 8行政
    /**
     * 自动上传
     */
    autoUpload?: boolean;
    /**
     * 是否显示删除按钮
     */
    showRemoveButton?: boolean;
    /**
     * 照片墙是否显示预览按钮
     */
    showPreviewButton?: boolean;
    /**
     * 是否显示文件列表
     */
    showFileList?: boolean;
    /**
     * 选中的图片id
     */
    imgSelectedId?: number;
    /**
     * 隐藏遮罩，不隐藏不能点击图片
     */
    hiddenMask?: boolean;
    /**
     * 登录背景照片墙特用
     */
    loginBgSetting?: boolean;
  }>(),
  {
    fileTypeList: () => [],
    listType: 'text',
    limit: 0,
    draggable: false,
    autoUpload: false,
    showRemoveButton: true,
    showPreviewButton: true,
    showFileList: true
  }
);
const submit = async (e) => {
  // for (const item of uploadList.value) {
  //   await aa(item);
  // }
};
const uploadFileStore = useUploadFileStore();
const uploadList = ref<any[]>([]);
const uploadRef = ref();

// ('[{"fileName":"2023-10-11 功能测试情况.docx","fileUrl":"https://linkease-hr-file.oss-cn-shenzhen.aliyuncs.com/0f48982b-af95-4d22-9cdf-12c900eb65f3.docx","id":398},{"fileName":"波衫.jpeg","fileUrl":"https://linkease-hr-file.oss-cn-shenzhen.aliyuncs.com/e145f2a4-e6c9-4669-9fc3-503318063583.jpeg","id":399}]');

const setUploadList = () => {
  const list = cloneDeep(uploadList.value);
  props.fileList?.forEach((item) => {
    const { fileId, fileUrl, fileName, uid } = item;
    if (
      !list.some(
        (upload: any) =>
          uid === upload.uid ||
          fileUrl === upload.url ||
          fileUrl === upload?.response?.DownloadPath
      )
    ) {
      uploadList.value.push({
        name: fileName,
        status: 'done',
        url: fileUrl,
        uuid: uid,
        response: { fileId, fileUrl, fileName }
      });
    }
  });
};
setUploadList();

watch(
  () => props.fileList,
  () => setUploadList()
);

const emit = defineEmits([
  'update:fileList',
  'uploadOk',
  'setBgImg',
  'delBgImg'
]);
const success = (fileItem: any) => {
  console.log('上传完成后回调', fileItem);
  emit('uploadOk', fileItem);
  uploadList.value
    .filter(({ status }) => status === 'done')
    .map((item: any) => {
      console.log('item', item);
      return {
        fileId: item.response.id,
        fileUrl: item.response.DownloadPath,
        fileName: item.response.useFileName
      };
    });
  // emit(
  //   'update:fileList',
  //   uploadList.value
  //     .filter(({ status }) => status === 'done')
  //     .map((item: any) => {
  //       console.log('item', item);
  //       return {
  //         fileId: item.response.id,
  //         fileUrl: item.response.DownloadPath,
  //         fileName: item.response.useFileName
  //       };
  //     })
  // );
};
//上传前校验
const beforeUpload = async (file: File) => {
  const { maxSize, fileTypeList } = props;
  // if (maxSize && file.size > maxSize) {
  //   Message.warning(`文件过大,不可超过${(maxSize / 1048576).toFixed(2)}M`);
  //   return Promise.reject();
  // }
  const fileType = file.name.slice(file.name.lastIndexOf('.'));
  if (!fileTypeList.includes(fileType)) {
    Message.warning('文件类型错误');
    Promise.reject();
  }
  return Promise.resolve(file);
};
let option1: any;
//上传操作
const customRequest = async (option: any, option2: any, option3: any) => {
  // console.log(option, option2, option3);

  // console.log('uploadRef', uploadRef.value.submit);
  const { onProgress, onError, onSuccess, fileItem } = option;
  try {
    let uuid = '';
    const data = await uploadFileStore.addUpLoadList(
      fileItem.file,
      0,
      0,
      props.userId,
      0,
      0,
      props.type
    );
    fileItem.uuid = data.uuid;
    uuid = data.uuid;
    await uploadFileStore.edItUploadState(data.uuid, 'run', {
      onProgress,
      onError,
      onSuccess
    });
    // const res = await uploadFileStore.runUpload();
    console.log(666, uploadFileStore.uploadModelList);
    if (props.autoUpload) return;
    fileItem.response = uploadFileStore.uploadModelList;
  } catch (err: unknown) {
    console.log(err);
  }
};

const aa = async (fileItem) => {
  try {
    let uuid = '';
    const data = await uploadFileStore.addUpLoadList(
      fileItem.file,
      0,
      0,
      props.userId,
      0,
      0,
      props.type
    );
    fileItem.uuid = data.uuid;
    uuid = data.uuid;
    await uploadFileStore.edItUploadState(data.uuid, 'run', 'aa');
    // const res = await uploadFileStore.runUpload();
    console.log(777, uploadFileStore.uploadModelList);
    fileItem.response = uploadFileStore.uploadModelList;
  } catch (err: unknown) {
    console.log(err);
  }
};

const beforeRemove = async (fileItem: any) => {
  console.log(fileItem);
  if (fileItem.status === 'done') {
    const res = await deleteFile({
      id: fileItem.response.id,
      type: props.type
    });
    if (res === '删除成功')
      uploadList.value.splice(
        uploadList.value.findIndex(
          (ele) => ele.response.id === fileItem.response.id
        ),
        1
      );
  }
  if (fileItem.status === 'uploading') {
    uploadFileStore.delUpLoadList(fileItem.uuid);
    uploadList.value.splice(
      uploadList.value.findIndex((ele) => ele.uuid === fileItem.uuid),
      1
    );
  }
};

// const beforeRemove = async (fileItem: any) => {
//   console.log(fileItem);
//   if (fileItem.status === 'done') {
//     const res = await deleteFile({
//       id: fileItem.response.id,
//       type: props.type
//     });
//     if (res === '删除成功') {
//       const index = uploadList.value.findIndex(
//         (ele) => ele.response.id === fileItem.response.id
//       );
//       uploadList.value.splice(index, 1);
//     }
//   }
//   if (fileItem.status === 'uploading') {
//     uploadFileStore.delUpLoadList(fileItem.uuid);
//     const index = uploadList.value.findIndex(
//       (ele) => ele.uuid === fileItem.uuid
//     );
//     uploadList.value.splice(index, 1);
//   }
// };
//上传的文件状态发生改变时触发
const change = (files, fileItem) => {
  // console.log(fileList, fileItem);
  uploadList.value = files;
  console.log(0, files);
};
const setLoginBgImg = (id: number) => {
  emit('setBgImg', id);
};
const delImg = (id: number) => {
  emit('delBgImg', id);
};
defineExpose({
  uploadList,
  submit
});
</script>

<style scoped>
::deep(.arco-upload-progress) {
  display: none;
}

:deep(.arco-upload-list-picture) {
  /* border: 1px solid #e30808; */
  height: 150px;
  width: 250px;

  box-sizing: border-box;
  .img {
    border: 1px solid #eee;
    padding: 10px;
    box-sizing: border-box;
    height: 150px;
    width: 100%;
    border-radius: 5px;
    &:hover {
      border-color: #0057f9;
      background-color: #e3ecfc;
    }
  }
  .img-selected {
    border-color: #0057f9;
    background-color: #e3ecfc;
  }
  .hiddenMask {
    position: absolute;
    z-index: 999;
  }
}
:deep(.arco-upload-picture-card) {
  height: 150px !important;
  width: 250px !important;
}
</style>
